package com.ctfo.ulcp.exp.db

import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.jdbcclient.JDBCPool
import io.vertx.kotlin.coroutines.await
import io.vertx.kotlin.coroutines.coAwait
import io.vertx.sqlclient.SqlConnection

const val SYSTEM_JDBC_URL = "jdbc:h2:./data/ulcp;DB_CLOSE_DELAY=-1;CACHE_SIZE=51200"

fun createJDBCPool(vertx: Vertx?): JDBCPool {
    val conf = JsonObject()
        .put("url", SYSTEM_JDBC_URL)
        .put("max_pool_size", 5)

    return JDBCPool.pool(vertx, conf)
}


suspend fun runTx(pool: JDBCPool, block: suspend (SqlConnection) -> Unit) {
    val conn = pool.connection.coAwait()
    val tx = conn.begin().coAwait()
    try {
        block(conn)
        tx.commit()
    } catch (err: Exception) {
        tx.rollback()
        throw err
    } finally {
        conn.close()
    }
}